import { ZPackOptions } from './Types';
import os = require('os');
import Path = require('path');

export const StandardModules = new Set(['assert', 'buffer', 'child_process', 'cluster', 'console', 'constants', 'crypto',
    'dgram', 'dns', 'domain', 'events', 'fs', 'http', 'https', 'module', 'net', 'os', 'path', 'punycode',
    'process', 'querystring', 'readline', 'repl', 'stream', '_stream_duplex', '_stream_passthrough',
    '_stream_readable', '_stream_transform', '_stream_writable', 'string_decoder', 'sys', 'timers', 'tls',
    'tty', 'url', 'util', 'vm', 'zlib', 'ZPackStub', 'v8'
]);

export function isSysPath(s: string) {
    return StandardModules.has(s);
}

export function isExternalPath(s: string, opt: ZPackOptions) {
    return s in opt.external;
}

export function isSubDir(dir1: string, dir2: string) {
    if (os.platform().toLowerCase().startsWith('win')) {
        dir1 = dir1.toLowerCase().replace(/\\/g, '/');
        dir2 = dir2.toLowerCase().replace(/\\/g, '/');
    }
    return dir2.startsWith(dir1);
}

export function appendExt(s: string, ext: string) {
    if (!s.toLowerCase().endsWith(ext)) {
        return s + ext;
    } else {
        return s;
    }
}

export function joinPath(...path: string[]) {
    let out = Path.join(...path).replace(/\\/g, '/');
    if (out.endsWith('/')) {
        out = out.slice(0, -1);
    }
    if (!out.match(/^([a-zA-Z]:)?\//)) {
        out = '/' + out;
    }
    return out;
}

export function concatHost(path: string, host: string) {
    if (host) {
        if (host.endsWith('/')) {
            host = host.slice(0, -1);
        }
        path = host + path;
    }
    return path;
}